/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionedt.enseignants;

import gestionedt.controllers.CreneauJpaController;
import gestionedt.controllers.EnseignantJpaController;
import gestionedt.models.Enseignant;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 * 
 */
public class SaveAction extends org.apache.struts.action.Action {
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if(isCancelled(request))
            return mapping.findForward("cancel");

        EnseignantsForm eForm = (EnseignantsForm) form;
        Enseignant enseignant = eForm.getEnseignant();

        CreneauJpaController ctCreneau = new CreneauJpaController();
        int[] numsIndispo = eForm.getNumsIntIndispo();
        enseignant.setIndisponibilites(ctCreneau.findCreneauxByNums(numsIndispo));

        boolean nv = (enseignant.getId()==null || enseignant.getId() == 0);
        EnseignantJpaController ctEnseignant = new EnseignantJpaController();
        if(nv)
            ctEnseignant.create(enseignant);
        else {
            Enseignant e = ctEnseignant.findEnseignant(enseignant.getId());
            e.setNom(enseignant.getNom());
            e.setPrenom(enseignant.getPrenom());
            e.setIndisponibilites(enseignant.getIndisponibilites());
            ctEnseignant.edit(e);
        }

        return new ActionForward("/GererEnseignants.do?action=afficher" +
                                         "&idEnseignant="+enseignant.getId(), true);
    }
}
